package controller;

import com.jfinal.aop.Inject;
import com.jfinal.plugin.activerecord.Page;
import io.jboot.db.model.Columns;
import io.jboot.test.codegen.model.R;
import io.jboot.test.codegen.model.User;
import io.jboot.test.codegen.service.UserService;
import io.jboot.web.controller.JbootController;
import io.jboot.web.controller.annotation.RequestMapping;
import io.jboot.web.json.JsonBody;

import java.util.Map;

/**
 * @program: gulimall
 * @description:
 * @author: 江天赐
 * @create: 2023-05-23 19:34
 */
@RequestMapping("/user")
public class UserController extends JbootController {
    @Inject
    private UserService userService;

    public R add(@JsonBody User user) {
        userService.save(user);
        return R.ok();
    }

    public R delete(@JsonBody User user) {
        user.setDr(1);
        boolean update = userService.update(user);
        if (update) {
            return R.ok();
        }
        return R.error("删除失败！请重试");
    }

    public R addOrDelete(@JsonBody User user) {
        if (user.getId() != null) {
            //说明前端传过来的对象有id即该对象已经在数据库中存在
            user.setDr(1);
            userService.update(user);
        }
        userService.save(user);
        return R.ok();
    }

    public R update(@JsonBody User user) {
        User user1 = user.findById(user.getId());
        if (user1.getDr() == 0) {
            userService.update(user);
        } else {
            return R.error("抱歉！数据不存在");
        }
        return R.ok();
    }

    public R page(int pageNum, int pageSize, int id, String username, String name, String password) {
        Map<String, String> paras = getParas();
        Columns columns = new Columns();
        columns.ne("dr", 1).eq("id", paras.get("id")).eq("username", paras.get("username")).eq("password", paras.get("password"));
        Page<User> userPage = userService.paginateByColumns(Integer.parseInt(paras.get("pageNum").toString()), Integer.parseInt(paras.get("pageSize").toString()), columns);
        return R.ok().put("userPage", userPage);
    }

}
